﻿using System.Collections.Generic;
using System.Linq;

namespace SolidPrinciples.OpenClosed
{
    public enum DiscountKinds
    {
        NoDiscount,
        PercentDiscount
    }

    /// <summary>
    ///     OCP violations:
    ///     to introduce a new discount it's necessary to make two changes:
    ///     1. Update DiscountKinds enumeration
    ///     2. Update SumToPay method
    ///     May be improved in order to
    /// </summary>
    public class PointOfSaleTerminal
    {
        private readonly List<Product> _products = new List<Product>();
        private DiscountKinds _discountKind = DiscountKinds.NoDiscount;
        private decimal? _discountValue;

        public IEnumerable<Product> Products
        {
            get { return _products; }
        }

        public decimal SumToPay
        {
            get
            {
                switch (_discountKind)
                {
                    case DiscountKinds.NoDiscount:
                        {
                            return _products.Sum(x => x.Price);
                        }
                    case DiscountKinds.PercentDiscount:
                        {
                            decimal sumToPay = _products.Sum(x => x.Price);
                            return sumToPay - (sumToPay*(_discountValue.GetValueOrDefault()/100));
                        }
                    default:
                        return 0;
                }
            }
        }

        public void Apply(DiscountKinds discountKind, decimal? discountValue = null)
        {
            _discountKind = discountKind;
            _discountValue = discountValue;
        }

        public void Register(Product product, int amount)
        {
            for (int i = 0; i < amount; i++)
            {
                _products.Add(product);
            }
        }

        public decimal PayOff(decimal customerPayment)
        {
            return customerPayment - SumToPay;
        }
    }
}